package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    /**
     * 每次执行insert 操作时，自动填充
     * @param metaObject
     * */

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("----插入时填充执行了...");

        strictInsertFill(metaObject, "createTime", Date.class, new Date());
        strictInsertFill(metaObject, "createBy", String.class, String.valueOf(loadUserId()));
    }

    /**
     * 每次执行 update 操作时，自动填充
     * @param metaObject
     * */

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("----修改时填充执行了...");

        //默认执行方式，有值就不填充，没值才填充
//        strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
//        strictUpdateFill(metaObject, "updateBy", String.class, String.valueOf(loadUserId()));

        //新执行方式，不管有没有值都填充
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", String.valueOf(loadUserId()), metaObject);
    }

    /**
     * 获取当前登录人的ID
     * @return  登录人ID
     */
    public Long loadUserId() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            return loginUser.getUserId();
        }
        return 1L;
    }
}